package com.eppear.jpfm.framework.websocket.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import com.eppear.jpfm.framework.application.ApplicationUtils;
import com.eppear.jpfm.framework.common.ConfigConstants;
import com.eppear.jpfm.framework.common.Signature;
import com.eppear.jpfm.framework.constants.Constants;
import com.eppear.jpfm.framework.util.SignUtil;

/**
 * @ClassName Client
 * @Description websocket客户端管理器
 * @author JianFeng Zhang(张建锋)
 * @date 2017-09-27 下午11:44:01 http://lippeng.iteye.com/blog/2299509
 *       http://www.jdon.com/idea/javaee7/websocket2.html
 */
public class Client {
	/*
	 * 注意:
	 * 需要从配置文件取的,是服务器地址,token,是否自动连接的标志.
	 */
	private static Logger log = LoggerFactory.getLogger(Client.class);
	private static WebSocketConnectionManager manager;
	
	public static WebSocketConnectionManager buildClient() {
		ClientHandler ch = (ClientHandler) ApplicationUtils.getBean("clientHandler");
		String url = ConfigConstants.WEBSOCKET_URL + getUrlParm(createSign());
		log.debug("要连接的服务器地址及参数为:[{}]",url);
		StandardWebSocketClient client = new StandardWebSocketClient();
		manager = new WebSocketConnectionManager(client, ch, url);
		manager.start();

		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return manager;
	}
	
	/**
	 * 断开连接
	 */
	public static void disConnectClient() {
		if (manager !=null)
			manager.stop();
	}
	
	/**
	 * 根据配置文件中的配置,生成签名参数
	 */
	private static Signature createSign() {
		Signature st = new Signature();
		st.setId(Constants.WEBSOCKET_ID);
		st.setToken(Constants.WEBSOCKET_TOKEN);
		st = SignUtil.generateSign(st);		
		return st;
	}
	
	private static String getUrlParm(Signature sgt) {
		String parm="";
		parm += "?id="+sgt.getId();
		parm += "&timestamp="+ sgt.getTimestamp();
		parm += "&nonce="+sgt.getNonce();
		parm += "&signature="+ sgt.getSignature();
		return parm;
	}
}
